#include "WTSXSipService/SipSXServiceMgr.hpp"
#include "WTSXSipService/SipSXService.hpp"

#include "WTResipDll/SipDebugInfo.hpp"

namespace wtsxsip{

CSipSXServiceMgr* CSipSXServiceMgr::s_instance = NULL;

CSipSXServiceMgr::CSipSXServiceMgr(void)
{
}

CSipSXServiceMgr::~CSipSXServiceMgr(void)
{
}


CSipSXServiceMgr* CSipSXServiceMgr::instance()
{
    if (!s_instance){
        s_instance = new CSipSXServiceMgr();
    }
    return s_instance;
}


bool CSipSXServiceMgr::finit()
{
    return false;
}


ISipSXService* CSipSXServiceMgr::generateService()
{
    CSipSXService* pService = new CSipSXService();
    if (!insertService(pService))
    {
        ERROR_LINE("Generate service failed.");
        destroyService(pService);
        return NULL;
    }
    return pService;
}

//
//bool CSipSXServiceMgr::encodeKey(std::string& key, const wtsip::SUri& localInfo)
//{
//    if (localInfo.szIP.empty() || localInfo.iPort < 1024){
//        ERROR_LINE("Invalid IP or Port.");
//        return false;
//    }
//    ostringstream osm;
//    osm << localInfo.szIP << ":" << localInfo.iPort;
//    key = osm.str();
//    return true;
//}


bool CSipSXServiceMgr::insertService(ISipSXService* service)
{
    if (!service)
        return false;

    std::pair<std::set<ISipSXService*>::iterator, bool> ret;
    ret = m_servicePool.insert(service);
    if (!ret.second){
        ERROR_LINE("Pool has the same service.");
        return false;
    }
    return true;
}


bool CSipSXServiceMgr::destroyService(ISipSXService* service)
{
    if (!service)
        return false;

    std::set<ISipSXService*>::iterator it;
    it = m_servicePool.find(service);
    if (it != m_servicePool.end())
    {
        m_servicePool.erase(it);
    }
    service->stop();
    delete service;
    return true;
}



}//namespace
